<?php


namespace app\admin\model;
use think\Request;
use think\Model;

class Menu extends Model
{
    /**
     * 获取列表
     * @throws
     */
    public function getMenus(Request $request){
        $defaultConfig = [
            'query'     => $request->get(), //url额外参数
            'fragment'  => '', //url锚点
            'var_page'  => 'page', //分页变量
        ];
        $field = $request->get('search','');
        $keyword = $request->get('keyword','');
        $where = [];
        if($field && ($keyword || $keyword==='0' || $keyword===0)){
            $where[] = [$field,'like','%'.$keyword.'%'];
        }
        $list =  $this->where($where)->paginate($defaultConfig);
        return $list;

    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTree(){
        $menu = $this->order('parent_id,order')->select()->toArray();
        $tree = [];
        foreach ($menu as $key => $val){
            if($val['parent_id']==0){
                $tree[] = $val;
                unset($menu[$key]);
            }
        }
        foreach ($tree as $key => &$val){
            $val['child'] = $this->getChild($val,$menu);
            $val['has_child'] = !empty($val['child']);
        }
        return $tree;

    }

    /**
     * 获取儿子
     * @param $item
     * @param $data
     * @return array
     */
    public function getChild($item,&$data){
        $child = [];
        foreach ($data as $key => &$val){
            if($val['parent_id'] == $item['id']){
                $val['child'] = $this->getChild($val,$data);
                $val['has_child'] = !empty($val['child']);
                $child[] = $val;
                unset($data[$key]);
            }
        }
        return $child;
    }
}